package com.banggood.upms.converter;

import com.banggood.upms.bean.po.Tree;
import com.banggood.upms.bean.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XuChuangFeng
 * @date 2017/7/4
 */
@Component
public class TreeConverter {
    
    public Tree singleInputConverter(TreeVo vo) {
        return voToPo(vo);
    }

    public List<Tree> inputConverter(List<TreeVo> voList) {
        List<Tree> poList = new ArrayList<>();
        for(TreeVo vo : voList) {
            poList.add(voToPo(vo));
        }
        return poList;
    }

    public List<TreeVo> outputConverter(List<Tree> poList) {
        // #1，将poList转换成voList
        List<TreeVo> voList = transferToVoList(poList);
        // #2，转换成voMap
        Map<String, TreeVo> voMap = convertVoListToMap(voList);
        // #3，填充所有节点的子节点ID并放到到map里面,并且返回根节点
        List<TreeVo> topNodes = fillSubTreeIds(voMap);
        return topNodes;
    }

    private List<TreeVo> fillSubTreeIds(Map<String, TreeVo> voMap) {
        List<TreeVo> topNodes = new ArrayList<>();
        for(Map.Entry<String, TreeVo> entry : voMap.entrySet()) {
            TreeVo vo = entry.getValue();
            String parentId = vo.getParentId();
            if(!StringUtils.isEmpty(parentId)) {
                // 将子节点的ID放入父节点的子节点集合中
                voMap.get(parentId).addSubTreeId(entry.getKey());
                voMap.get(parentId).addSubTree(entry.getValue());
            } else {
                // 只有一个顶级节点
                TreeVo topNode = entry.getValue();
                topNodes.add(topNode);
            }
        }
        return topNodes;
    }

    private List<TreeVo> transferToVoList(List<Tree> poList) {
        List<TreeVo> voList = new ArrayList<>();
        for(Tree po : poList) {
            voList.add(poToVo(po));
        }
        return voList;
    }

    public TreeVo singleOutputConverter(Tree po) {
        return poToVo(po);
    }

    private TreeVo poToVo(Tree po) {
        TreeVo vo = new TreeVo();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    private Tree voToPo(TreeVo vo) {
        Tree po = new Tree();
        BeanUtils.copyProperties(vo, po);
        return po;
    }

    private Map<String, TreeVo> convertVoListToMap(List<TreeVo> voList) {
        Map<String, TreeVo> treeMap = new HashMap<>();
        for(TreeVo tree : voList) {
            treeMap.put(tree.getTreeId(), tree);
        }
        return treeMap;
    }
}
